package com.warrantyhotel.android.ui;

import android.app.Activity;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Xml.Encoding;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TextView;

import com.warrantyhotel.android.R;
import com.warrantyhotel.android.db.QueriesCodes;
import com.warrantyhotel.android.db.WarrantyHotelDBSchema.Inbox_RSS_Table;
import com.warrantyhotel.android.model.Keys;
import com.warrantyhotel.android.util.BitmapUtils;
import com.warrantyhotel.android.util.NotifyingAsyncQueryHandler;
import com.warrantyhotel.android.util.BitmapUtils.OnFetchCompleteListener;
import com.warrantyhotel.android.util.NotifyingAsyncQueryHandler.AsyncQueryListener;

public class InboxNewsDetail extends Activity implements AsyncQueryListener {

	private WebView webView;
	private ImageView rss_banner;
	private NotifyingAsyncQueryHandler mHandler;
	private TextView rssTextView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.inbox_news_detail);

		rssTextView = (TextView) findViewById(R.id.inbox_rss_title);
		rss_banner = (ImageView) findViewById(R.id.inbox_rss_banner);
		webView = (WebView) findViewById(R.id.inbox_rss_webView);
		webView.setBackgroundColor(Color.TRANSPARENT);
		String guid = getIntent().getExtras().getString(Keys._guid);
		mHandler = new NotifyingAsyncQueryHandler(getContentResolver(), this);
		retrieveNewsRSSbyId(guid);

	}

	private void retrieveNewsRSSbyId(String guid) {
		String[] projectionNews = { Inbox_RSS_Table._ID, Inbox_RSS_Table.GUID, Inbox_RSS_Table.LINK, Inbox_RSS_Table.GUID, Inbox_RSS_Table.TITLE,
				Inbox_RSS_Table.CONTENT, Inbox_RSS_Table.DESCRIPTION, Inbox_RSS_Table.LINK_BANNER };
		mHandler.startQuery(QueriesCodes.INBOX_NEWS, Inbox_RSS_Table.CONTENT_URI, projectionNews, Inbox_RSS_Table.GUID + " = '" + guid + "'", null, null);
	}

	@Override
	public void onQueryComplete(int token, Object cookie, Cursor cursor) {
		switch (token) {
		case QueriesCodes.INBOX_NEWS:
			if (cursor != null) {
				startManagingCursor(cursor);
				if (cursor.moveToFirst()) {
					String description = cursor.getString(cursor.getColumnIndex(Inbox_RSS_Table.CONTENT));
					webView.loadData(description, "text/html", Encoding.UTF_8.toString());
					String banner_link = cursor.getString(cursor.getColumnIndex(Inbox_RSS_Table.LINK_BANNER));
					BitmapUtils.fetchImage(getApplicationContext(), banner_link, new OnFetchCompleteListener() {
						@Override
						public void onFetchComplete(Object cookie, Bitmap result) {
							rss_banner.setImageBitmap(result);
						}
					});
					String title = cursor.getString(cursor.getColumnIndex(Inbox_RSS_Table.TITLE));
					rssTextView.setText(title);
				}
			}
			break;
		}

	}

}